package com.yungam.imcs.controller.hand_inspect.history;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yungam.common.bean.hand_inspect.ProcessInspectionHand;
import com.yungam.common.bean.hand_inspect.ProductInspectionHand;
import com.yungam.common.response.RetDTO;
import com.yungam.common.service.ProcessInspectionHandService;
import com.yungam.common.service.ProductInspectionHandService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Api(tags = "历史质量检验页面接口")
@RestController
@RequestMapping("/history_inspection")
public class HistoryHandInspectionController {

    @Resource
    private ProductInspectionHandService productInspectionHandService;
    @Resource
    private ProcessInspectionHandService processInspectionHandService;

    @ApiOperation("获取表格数据")
    @GetMapping("/tableData")
    public RetDTO<?> getHistoryTableData(@ApiParam("开始时间") String start,
                                         @ApiParam("结束时间") String end) {
        // 查询
        List<ProductInspectionHand> productHands = productInspectionHandService.list(new QueryWrapper<ProductInspectionHand>()
                .between("create_time", start, end).orderByDesc("create_time"));
        List<ProcessInspectionHand> processHands = processInspectionHandService.list(new QueryWrapper<ProcessInspectionHand>()
                .between("create_time", start, end).orderByAsc("create_time"));

        // 组装成树结构
        Map<String, List<ProcessInspectionHand>> map = Maps.newHashMap();
        for (ProcessInspectionHand ph : processHands) {
            List<ProcessInspectionHand> list = map.getOrDefault(ph.getProductSn(), Lists.newArrayList());
            list.add(ph);
            map.put(ph.getProductSn(), list);
        }

        for (ProductInspectionHand productHand : productHands) {
            productHand.setChildren(map.getOrDefault(productHand.getProductSn(), null));
        }

        return RetDTO.data(productHands);
    }

    @ApiOperation("保存检验信息")
    @PostMapping("/save")
    public RetDTO<?> save(@ApiParam("产品检验实体集合") @RequestBody List<ProductInspectionHand> data) {
        int len = data.size();
        if (len == 0) return RetDTO.success();

        for (ProductInspectionHand pi : data) {
            productInspectionHandService.updateById(pi);
            if (pi.getChildren() == null || pi.getChildren().size() == 0)  continue;
            for (ProcessInspectionHand child : pi.getChildren()) {
                processInspectionHandService.updateById(child);
            }
        }
        return RetDTO.success();
    }
}
